package org.gdpu.Service.Impl;

import org.gdpu.Service.CampusService;
import org.gdpu.Service.DormitoryService;
import org.gdpu.base.DaoSupport;
import org.gdpu.model.College;
import org.gdpu.model.Dormitory;
import org.gdpu.model.DormitoryState;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.persistence.Query;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by HEWI2 on 2/17/14.
 */

@Service
@Transactional
public class DormitoryServiceImpl extends DaoSupport<Dormitory> implements DormitoryService {

    private CampusService campusService;

    @Override
    public Dormitory findById(String dormitory,String campusName){
        Map<String, Object> params = new HashMap<String, Object>();
        String dormitoryId = dormitory;
        if(dormitory.length() == 4)
            dormitoryId = dormitory.substring(0,1) + "-" + dormitory.substring(1,4);
        params.put("dormitoryId", dormitoryId.toUpperCase());
        params.put("campus", campusService.findByCampusByName(campusName));
        return (Dormitory) this.findSpecialObject(Dormitory.class, params);
    }

    @Override
    public List<Dormitory> findByCampus(String campusName){
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("dormitoryState", DormitoryState.EMPTY);
        params.put("campus", campusService.findByCampusByName(campusName));
        return (List<Dormitory>)this.findByFields(Dormitory.class, params);
    }

    @Override
    public List<String> findBuilding(String campus){
        Query query = em.createQuery("SELECT DISTINCT SubString(d.dormitoryId,1,1) from Dormitory d where d.campus.campusId=?1");
        query.setParameter(1, campusService.findByCampusByName(campus).getCampusId());
        return query.getResultList();
    }

    @Resource(name = "campusServiceImpl")
    public void setCampusService(CampusService campusService) {
        this.campusService = campusService;
    }
}
